﻿
var yuiAjaxObject = {
 	JSONParse:function(o) {
		var messages = []; 
		try { 
		    messages = YAHOO.lang.JSON.parse(o.responseText); 
		    return messages;
		} catch (x) { 
		    return null; 
		}
	},
	startRequest:function(method, url, params, success, failure, scope) {
	    var callback = {
	        success:success,
	        failure:failure,
	        scope: scope
	    };
	    if (params != null && params != "") {
	        url += "?" + params;
	    }
	    YAHOO.util.Connect.asyncRequest(method, url, callback);
	}
};

window.loadingPanel = function() { 
    if (window._loadingPanel) {
        return window._loadingPanel;
    }
    
    window._loadingPanel =  
            new YAHOO.widget.Panel("wait",   
                { width:"240px",  
                  fixedcenter:true,  
                  close:false,  
                  draggable:false,  
                  zindex:11110, 
                  modal:true, 
                  visible:false 
                }  
            ); 
	 
    window._loadingPanel.setHeader("Loading, please wait..."); 
    window._loadingPanel.setBody('<img src="/admin/resources/images/loading.gif" />'); 
    window._loadingPanel.render(document.body); 
    return window._loadingPanel;
};

String.prototype.startsWith = function(str) {
    return (this.match("^"+str)==str);
}
String.prototype.endsWith = function(str) {
    return (this.match(str+"$")==str);
}

String.prototype.trimLeftStr = function(trm) {
    var str = this;
    if (trm == null || trm === "") return str;
    while(str.startsWith(trm)) {
        str = str.substring(str.indexOf(trm) + 1);
    }
    return str;
}

String.prototype.trimRightStr = function(trm) {
    var str = this;
    if (trm == null || trm === "") return str;
    while(str.endsWith(trm)) {
        str = str.substring(0, str.lastIndexOf(trm));
    }
    return str;
}

var mapPath = function(path1, path2) {
    path1 = path1.trimRightStr("/");
    path2 = path2.trimLeftStr("/").trimRightStr("/");
    
    if (path2.startsWith("..")) {
        path1 = path1.substring(0, path1.lastIndexOf("/"));
        path2 = path2.trimLeftStr(".").trimLeftStr("/");
    }
    return path1 + "/" + path2 + "/";
}

var appendFolder = function(i, absolute_folder, related_folder, folder_name, cont, dialog) {
    var imgi = document.createElement( 'img' );
    imgi.id = cont.id + '_f_img_' + (i+1);
    imgi.src = "resources/images/folder.jpg";
    imgi.style.width = "100px";
    imgi.style.maxWidth = "100px";
    imgi.style.maxHeight = "100px";
    imgi.style.cursor = 'pointer';
    imgi.alt = folder_name;
    
    var divi = document.createElement( 'div' );
    divi.id = cont.id + '_f_div_' + (i+1);
    divi.style.cursor = 'pointer';
    divi.style.marginTop = "6px";
    divi.style.textAlign = "center";
    divi.innerHTML = folder_name;
    
    var linki = document.createElement( 'a' );
    linki.id = cont.id + '_f_a_' + (i+1);
    linki.style.display = 'block';
    linki.style.width = "100px";
    linki.style.marginTop = "5px";
    linki.style.marginRight = "5px";
    linki.style.height = "120px";
    linki.style.overflow = "hidden";
    linki.style.cssFloat = 'left';
    linki.style.cursor = 'pointer';
    linki.style.border = 'solid 1px #999';
    linki.style.padding = '2px';
    linki.parentDialog = dialog;
    linki.parentEditor = dialog.getParentEditor();
    linki.title = folder_name;
    
    linki.appendChild(imgi);
    linki.appendChild(divi);
    linki.onclick = function() {
        loadImages(mapPath(related_folder, this.title), this.parentDialog, this.parentEditor);
    };
    
    cont.appendChild(linki);
}

var appendImage = function(i, absolute_folder, related_folder, imgSrc, imgCont, dialog) {
    var imgi = document.createElement( 'img' );
    imgi.id = imgCont.id + '_i_img_' + (i+1);
    imgi.src = absolute_folder + imgSrc;
    //imgi.style.width = "100px";
    imgi.style.maxWidth = "100px";
    imgi.style.maxHeight = "100px";
    imgi.style.cursor = 'pointer';
    imgi.style.position = "absolute";
    imgi.style.top = "0";
    imgi.style.bottom = "0";
    imgi.style.left = "0";
    imgi.style.right = "0";
    imgi.style.margin = "auto";
    imgi.alt = imgSrc;
    
    var imgci = document.createElement( 'div' );
    imgci.id = imgCont.id + '_i_imgc_' + (i+1);
    imgci.style.width = "100px";
    imgci.style.height = "100px";
    imgci.style.cursor = 'pointer';
    imgci.style.position = 'relative';
    imgci.style.backgroundColor = "#fff";
    imgci.appendChild(imgi);
    
    var divi = document.createElement( 'div' );
    divi.id = imgCont.id + '_i_div_' + (i+1);
    divi.style.cursor = 'pointer';
    divi.style.marginTop = "6px";
    divi.style.textAlign = "center";
    divi.innerHTML = imgSrc;
    
    var linki = document.createElement( 'a' );
    linki.id = imgCont.id + '_i_a_' + (i+1);
    linki.style.display = 'block';
    linki.style.width = "100px";
    linki.style.marginTop = "5px";
    linki.style.marginRight = "5px";
    linki.style.height = "120px";
    linki.style.overflow = "hidden";
    linki.style.cssFloat = 'left';
    linki.style.cursor = 'pointer';
    linki.style.border = 'solid 1px #999';
    linki.style.padding = '2px';
    linki.parentDialog = dialog;
    linki.parentEditor = dialog.getParentEditor();
    linki.title = imgSrc;
    
    linki.appendChild(imgci);
    linki.appendChild(divi);
    linki.onclick = function() {
        var imgUrl = this.firstChild.firstChild.getAttribute("src");
        this.parentDialog.getContentElement('general', 'url').setValue(imgUrl);
        this.parentDialog.click('ok');
    };
    
    imgCont.appendChild(linki);
}

var bindResult = function(result, dialog, editor) {
    var imgCont = document.getElementById(editor.id + '_imgc');
    var absolute_folder = result.absolute_folder;
    var related_folder = result.related_folder;
    dialog.related_folder = related_folder;
    
    if (related_folder === "/") {
    } else {
        appendFolder(-1, absolute_folder, related_folder, "..", imgCont, dialog);
    }
    
    if (result.folders) {
        for (var i = 0; i < result.folders.length; i++) {
            var imgSrc = result.folders[i].src;
            
            appendFolder(i, absolute_folder, related_folder, imgSrc, imgCont, dialog);
        }
    }
    if (result.images) {
        for (var i = 0; i < result.images.length; i++) {
            var imgSrc = result.images[i].src;
            
            appendImage(i, absolute_folder, related_folder, imgSrc, imgCont, dialog);
        }
    }
}

var loadImages = function(path, dialog, editor) {
    var imgCont = document.getElementById(dialog.getParentEditor().id + '_imgc');
    imgCont.innerHTML = '';
    
    var callback = {
        success:function(o) {
            var imgCont = document.getElementById(editor.id + '_imgc');
            imgCont.innerHTML = '';
            
            var result = yuiAjaxObject.JSONParse(o);
            if (result) {
                bindResult(result, dialog, editor);
            }
        },
        failure:function(o) {
        }
    };
    yuiAjaxObject.startRequest('GET', 'ImageListProvider.aspx', 'file=' + encodeURIComponent(path) + '&id='+editor.id, callback.success, callback.failure, this);
}


CKEDITOR.plugins.add( 'selectImage',
{
	init: function( editor )
	{
		editor.addCommand( 'selectImageDialog', new CKEDITOR.dialogCommand( 'selectImageDialog' ) );
		
		editor.ui.addButton( 'SelectImage', {
	        label: 'Insert an image by select it.',
	        command: 'selectImageDialog',
	        icon: this.path + 'images/selectimage.gif'
        });
	}
});

CKEDITOR.dialog.add( 'selectImageDialog', function( editor )
{
    return {
		title : 'Select an image to insert',
		minWidth : 684,
		minHeight : 508,
		contents :
		[
			{
				id : 'general',
				label : 'Settings',
				elements :
				[
					{
						type : 'html',
						html : 'This dialog window lets you create simple image for your website, by browser and select it.'		
					},
					{
						type : 'text',
						id : 'url',
						label : 'URL',
						validate : CKEDITOR.dialog.validate.notEmpty( 'The link must have an URL.' ),
						required : true,
						commit : function( data )
						{
							data.url = this.getValue();
						}
					},
					{
						type : 'text',
						id : 'title',
						label : 'Title',
						required : false,
						commit : function( data )
						{
							data.title = this.getValue();
						}
					},
					{
						type : 'file',
						id : 'fuImg',
						label : '<b style="font-weight: bold;">Or select an image to upload</b>',
						required : false,
						html : '<div id="' + editor.id + '_fuImg" style="width: 684px; height: 395px; overflow: auto;"><div>'
					},
					{
					    type : 'checkbox',
	                    id : 'chkLayerMask',
	                    label : 'Đính kèm logo (đối với file ảnh *.jpg)',
	                    'default' : false,
						commit : function( data )
						{
							data.addLayerMask = this.getValue();
						}
					},
					{
						type : 'html',
						id : 'imgc',
						html : '<div id="' + editor.id + '_imgc" style="width: 684px; height: 395px; overflow: auto;"><div>'
					}
				]
			}
		],onShow : function(o)
        {
            var imgCont = document.getElementById(this.getParentEditor().id + '_imgc');
            if (!imgCont || imgCont.innerHTML.trimLeftStr(' ') == '' || imgCont.innerHTML.trimLeftStr(' ').trimRightStr(' ') == '<div></div>') {
                loadImages('/', this, this.getParentEditor());
            }
            
            this._.contents.general.fuImg.getInputElement().$.dialog = this;
            this._.contents.general.fuImg.getInputElement().$.onchange = function() {
                var fuImg = this;
                if (fuImg.files != null && fuImg.files.length > 0) {
                    if (NTTHAO.util.isImageFile(fuImg.value)) { // is image file
                        var data = {};
			            this.dialog.commitContent( data );
                    
                        window.loadingPanel().show();
    				    
				        var fd = new FormData();
                        fd.append('fuImg', fuImg.files[0]);
                        fd.append('path', this.dialog.related_folder);
                        fd.append('addLayerMask', data.addLayerMask ? "1" : "0");
                        var xhr = null;
                        if (window.XMLHttpRequest) {
                            xhr = new XMLHttpRequest();
                        }
                        else { // for older IE 5/6
                            xhr = new ActiveXObject("Microsoft.XMLHTTP");
                        }                        xhr.dialog = this.dialog;
                        xhr.addEventListener("load", function(e) { 
                                                        this.dialog.getContentElement('general', 'url').setValue(e.target.responseText);
                                                    }, false);
                        xhr.addEventListener("error", function(e) { 
                                                        alert('Có lỗi xảy ra trong quá trình upload file.\n Vui lòng đăng nhập lại.');
                                                        window.loadingPanel().hide();
                                                    }, false);
                        xhr.open("POST", '/admin/EditorFileUploader.aspx', false);
                        xhr.send(fd);
                        xhr.open('GET', '/admin/RefreshSessionState.aspx', false);
                        this.value = '';
                        loadImages(this.dialog.related_folder, this.dialog, this.dialog.getParentEditor());
                        
                        window.loadingPanel().hide();
                    }
                    else {
                        fuImg.value = '';
                        alert('Chức năng này chỉ hỗ trợ file ảnh với các định dạng: *.jpg, *.jpeg, *.jpe, *.png, *.gif, *.bmp');
                    }
				}
            };
            /*
	        document[this.getParentEditor().id] = this.getParentEditor();
	        
	        var callback = {
                success:function(o) {
                    var dialog = this;
                    
	                var imgCont = document.getElementById(dialog.getParentEditor().id + '_imgc');
	                document[dialog.getParentEditor().id + '_imgc'] = imgCont;
        	        
                    imgCont.innerHTML = '';
                    
                    var result = yuiAjaxObject.JSONParse(o);
                    if (result) {
                        bindResult(result, dialog, dialog.getParentEditor());
                    }
                },
                failure:function(o) {
                }
            };
	        
	        //yuiAjaxObject.startRequest('GET', 'ImageListProvider.aspx', 'id='+this.getParentEditor().id, callback.success, callback.failure, this);
	        */
        },
		onOk : function()
		{
			var dialog = this,
				data = {},
				img = editor.document.createElement( 'img' );
			this.commitContent( data );

			img.setAttribute( 'src', data.url );

			if ( data.title )
				img.setAttribute( 'title', data.title );

			editor.insertElement( img );
		}
	};
});